package com.cwm.common.config;

import com.cwm.common.VO.ResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collection;
import java.util.List;

/**
 * 全局返回处理
 * @author pya
 */
@Slf4j
@RestControllerAdvice
public class GlobalResultHandler implements ResponseBodyAdvice<Object> {

    @Value("#{'${passGlobalResultHandlerPath:}'.split(',')}")
    private List<String> passPath;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
//        Class<?> controllerClass = methodParameter.getDeclaringClass();
//        Method controllerMethod = methodParameter.getMethod();
//        if (controllerClass.isAnnotationPresent(PassGlobalResult.class) || controllerMethod.isAnnotationPresent(PassGlobalResult.class)) {
//            return false;
//        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String path = serverHttpRequest.getURI().getPath();
        boolean skip = o instanceof ResultWrapper || (!CollectionUtils.isEmpty(passPath) && passPath.contains(path));
        if (skip) {
            return o;
        }
        return ResultWrapper.ok(o);
    }


}
